package cn.edu.bupt.scidata.service;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class IDSearch {
    @Autowired
    RestHighLevelClient client;
    public List<Integer> getids(String keyword, String lang) {
        String indice = "zcwpaper1";
        String matchField1 = "keywords";
        String matchField2 = "title";
        QueryBuilder qb2;
        float score = 0f;
        if(Objects.equals(lang, "EN")){
            indice = "zcwenpaper";
            String matchField = "cn_name";;
            MatchQueryBuilder mqb = QueryBuilders
                    .matchQuery(matchField,keyword);
            qb2 = QueryBuilders.boolQuery()
                    .must(mqb);
        }else {
            MatchQueryBuilder mqb1 = QueryBuilders
                    .matchQuery(matchField1,keyword);
            MatchQueryBuilder mqb2 = QueryBuilders
                    .matchQuery(matchField2,keyword);
            qb2 = QueryBuilders.boolQuery()
                    .must(mqb1)
                    .must(mqb2);
            score = 15f;
        }
        SearchRequest request = new SearchRequest(indice);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        MatchQueryBuilder mqb1 = QueryBuilders
//                .matchQuery(matchField1,keyword);
//        MatchQueryBuilder mqb2 = QueryBuilders
//                .matchQuery(matchField2,keyword);
//        QueryBuilder qb2 = QueryBuilders.boolQuery()
//                .must(mpq);
        sourceBuilder.minScore(score);
        sourceBuilder.query(qb2);
        sourceBuilder.from(0).size(10000);

        request.source(sourceBuilder);
        Set<Integer> paperIds = new HashSet<>();
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            for (SearchHit documentFileds : response.getHits().getHits()) {
                paperIds.add((Integer) documentFileds.getSourceAsMap().get("id"));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return new ArrayList<>(paperIds);
    }
}
